Dynomotion

Group: DynoMotion Message: 8838 From: ricochetproducts Date: 1/1/2014
Subject: What Am I Doing Wrong?
For some reason this code will not work.  I have played with it all morning.  Please Help.


#include "KMotionDef.h"

#define hydpumpswitch 1038
#define coolpumpswitch 1039


// state variables for switch debouncing
int pumpState=0;
main()
{
/////Hydraulic Pump Control MOMENTARY BUTTON

int switchPressed = Debounce(ReadBit(hydpumpswitch),0,0,-1);
if (switchPressed == 1)    // If in this state, we are on first loop after switch pressed. 
{
if (pumpState == 1)
{
pumpState = 0; 
            ClearBit(155);  // Hydraulic pump off
ClearBit(149);                 // Vertical tool change valve closed
ClearBit(50);  // Button indicator lite off
}
else 
{
pumpState = 1; 
            SetBit(155);  // Hydraulic pump on
SetBit(149);                // Vertical tool change valve open
SetBit(50);   // Button indicator lite on
}
   }
///// Coolant Pump Control PUSH ON / PUSH OFF BUTTON
int result = ReadBit (coolpumpswitch);

WaitNextTimeSlice();
if (result == 1)
{
SetBit(152); // Coolant Pump on.
SetBit(51); // Coolant Pump indicator on.
}
       
        else
        {
                 ClearBit(152);      // Coolant Pump off.
                 ClearBit(51);      // Coolant Pump indicator off.
}     
}

#define DBTIME 300

// Debounce a bit
//
// return 1 one time when first debounced high 
// return 0 one time when first debounced low 
// return -1 otherwise 

int Debounce(int n, int *cnt, int *last, int *lastsolid)
{
int v = -1;
if (n == *last)  // same as last time?
{
if (*cnt == DBTIME-1)
{
if (n != *lastsolid)
{
v = *lastsolid = n;  // return debounced value
}
}
if (*cnt < DBTIME) (*cnt)++;
}
else
{
*cnt = 0;  // reset count
}
*last = n;
return v;
}
  @@attachment@@
Group: DynoMotion Message: 8840 From: Tom Kerekes Date: 1/1/2014
Subject: Re: What Am I Doing Wrong? [1 Attachment]
The Debounce() function is written using a non-blocking state machine approach where its state is saved away so that the function can exit and later come back an resume what it was doing.  This approach allows a single Thread to service a number of activities at the same time.  Three integer variables are required to keep track of the state.  Define and initialize 3 unique variables such as:

// state variables for switch debouncing
int hlast=0,hlastsolid=-1,hcount=0;

Then pass the addresses of these variables into the Debounce function to be used specifically for debouncing that one switch:

int switchPressed = Debounce(ReadBit(hydpumpswitch),&fcount,&flast,&flastsolid);

HTH
Regards
TK